import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Carwash } from 'src/schemas/carwash/carwash.interface';
import { User } from 'src/schemas/user/user.interface';
import { Order } from 'src/schemas/order/order.interface';
import { StatisticDto } from 'src/dto/dashboard.dto';
import { MomentService } from 'src/common/moment/moment.service';
import { OrderState } from 'src/dto/order.dto';

@Injectable()
export class DashboardService {
  constructor(
    @InjectModel('Carwash') private readonly carwashModel: Model<Carwash>,
    @InjectModel('User') private readonly userModel: Model<User>,
    @InjectModel('Order') private readonly orderModel: Model<Order>,
    private readonly momentService: MomentService,
  ) {}

  /**
   * 获取统计数据
   */
  async statistic(): Promise<StatisticDto> {
    const utcAdd8Date = this.momentService.utcAdd8Date;

    // 累计洗车点
    const cumulativeCarwashes = this.carwashModel.estimatedDocumentCount();

    // 累计用户
    const cumulativeUsers = this.userModel.estimatedDocumentCount();

    // 今日新增用户
    const todayNewUsers = this.userModel
      .find({
        creationTime: {
          $gte: utcAdd8Date,
        },
      })
      .countDocuments();

    // 累计订单
    const cumulativeOrders = this.orderModel.estimatedDocumentCount();

    // 今日新增订单
    const todayNewOrders = this.orderModel
      .find({
        creationTime: {
          $gte: utcAdd8Date,
        },
      })
      .countDocuments();

    // 累计营业额
    const cumulativeTurnover = this.orderModel.aggregate([
      {
        $match: { state: OrderState.Completed },
      },
      { $group: { _id: null, count: { $sum: '$amount' } } },
    ]);

    // 今日营业额
    const todayNewTurnover = this.orderModel.aggregate([
      {
        $match: {
          creationTime: { $gte: utcAdd8Date },
          state: OrderState.Completed,
        },
      },
      { $group: { _id: null, count: { $sum: '$amount' } } },
    ]);

    const result = await Promise.all([
      cumulativeCarwashes,
      cumulativeUsers,
      todayNewUsers,
      cumulativeOrders,
      todayNewOrders,
      cumulativeTurnover,
      todayNewTurnover,
    ]);

    return {
      // 累计洗车点
      cumulativeCarwashes: result[0],

      // 累计用户
      cumulativeUsers: result[1],

      // 今日新增用户
      todayNewUsers: result[2],

      // 累计订单
      cumulativeOrders: result[3],

      // 今日新增订单
      todayNewOrders: result[4],

      // 累计营业额
      cumulativeTurnover: result[5][0]?.count || 0,

      // 今日营业额
      todayNewTurnover: result[6][0]?.count || 0,
    } as StatisticDto;
  }
}
